﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xaml;
using System.CodeDom;
using System.Diagnostics;

namespace NeuroSpeech.XamlExtensions
{
    public class ItemsWriter : DefaultWriter
    {

        public ItemsWriter():base(XamlLanguage.Items)
        {

        }

        public override void StartMember(XamlCodeContext context)
        {
            //context.XamlValue.StartCollection();
            context.Peek.Value.CreateCollection();
        }

        #region public override void  WriteEndMember(XamlCodeContext context)
        public override void EndMember(XamlCodeContext context)
        {
            if (!context.Peek.IsValueCollection)
                return;
            List<CodeStatement> statements = context.Statements;
            XamlItem peek = context.Peek;
            foreach (XamlItemExpression exp in context.Peek.Value.Collection)
            {
                //init.Statements.Add(new CodeCommentStatement
                //{
                //    Comment = new CodeComment("ItemsWriter.EndMember")
                //});
                CodeMethodInvokeExpression method = new CodeMethodInvokeExpression
                {
                    Method = new CodeMethodReferenceExpression { 
                        TargetObject = ParentTarget(peek.TargetObject),
                        MethodName = "Add"
                    }
                };

                if (IsDictionary(peek.Type.UnderlyingType)) {
                    method.Parameters.Add(new CodePrimitiveExpression(exp.Item.Key));
                }

                method.Parameters.Add(exp.Expression);
                statements.Add(new CodeExpressionStatement
                {
                    Expression = method
                });
            }
            //context.XamlValue.Collection = null;
            //context.XamlValue.Value = null;

        }

        private bool IsDictionary(Type type)
        {
            foreach (Type iftype in type.GetInterfaces()) {
                if (iftype.FullName == "System.Collections.IDictionary")
                    return true;
            }
            return false;
        }

        private CodeExpression ParentTarget(CodeExpression codeExpression)
        {
            CodePropertyReferenceExpression pr = codeExpression as CodePropertyReferenceExpression;
            if (pr != null)
                return pr.TargetObject;
            CodeFieldReferenceExpression fr = codeExpression as CodeFieldReferenceExpression;
            if (fr != null)
                return fr.TargetObject;
            return codeExpression;
        }
        #endregion

        /*public override void EndObject(XamlCodeContext context)
        {
            //base.EndObject(context);
        }*/
    }
}
